#include <stdio.h>
#include <stdlib.h>
#include <mqueue.h>
#include <string.h>
#include <signal.h>

#define QUEUE_NAME  "/mcu_command_queue"
#define MAX_MSG_SIZE 1024

volatile sig_atomic_t running = 1;

void handle_signal(int sig) {
    running = 0;
}

int main() {
    signal(SIGINT, handle_signal);
    
    mqd_t mq = mq_open(QUEUE_NAME, O_RDONLY);
    if (mq == (mqd_t)-1) {
        perror("mq_open failed");
        return EXIT_FAILURE;
    }

    // 验证消息大小
    struct mq_attr attr;
    mq_getattr(mq, &attr);
    if (attr.mq_msgsize > MAX_MSG_SIZE) {
        fprintf(stderr, "Message size mismatch (%ld > %d)\n",
                attr.mq_msgsize, MAX_MSG_SIZE);
        mq_close(mq);
        return EXIT_FAILURE;
    }

    printf("Ready. Queue stats: %ld messages pending\n", attr.mq_curmsgs);
    
    while (running) {
        char buffer[MAX_MSG_SIZE + 1] = {0};
        ssize_t bytes = mq_receive(mq, buffer, MAX_MSG_SIZE, NULL);
        
        if (bytes > 0) {
            buffer[bytes] = '\0';
            printf("[%ld bytes] %s\n", bytes, buffer);
        } else if (bytes == -1) {
            perror("mq_receive");
            sleep(1);
        }
    }

    mq_close(mq);
    printf("Clean exit\n");
    return 0;
}